<template>
    <el-form :model="formData" :rules="rules" ref="formObj" label-width="80px">
		<el-form-item label="类别名称" prop="name">
			<el-input maxLength="20" v-model="formData.name" placeholder="请输入类别名称"></el-input>
		</el-form-item>
		<el-form-item label="类别说明" prop="description">
			<el-input type="textarea" :rows="5" v-model="formData.description" placeholder="请输入类别说明"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :icon="IconSave" @click="save()">保存</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup>
import url from './pathUtil'
import { reactive, ref } from 'vue'
import IconSave from '@/components/icons/IconSave'
import { get,post } from '@/plugins/axios'
//接收父组件参数
const emits = defineEmits(['update:show', 'getTableData'])
const props = defineProps(['id', 'parentId', 'level'])
const fileList = reactive([])
//表单数据
const formData = reactive({
	id: null,
	name: '',
	description: '',
	parentId: null,
	level: null
})
//校验规则
const rules = reactive({
	name: {
		required: true, message: '类别名称不能为空', trigger: 'blur'
	},
	description: {
		required: true, message: '类别说明不能为空', trigger: 'blur'
	}
})

const formObj = ref()
//如果id不为空 给id赋值
if(props.id) {
	formData.id = props.id
	getById()
} else {
	formData.level = props.level
	formData.parentId = props.parentId
}

function save() {
	console.dir(formData)
	post(props.id ? url.update : url.add, formData, content =>{
		emits('update:show', false)
		emits('getTableData')
	},formObj)
}

function getById() {
	get(url.getById, { id: props.id }, content => {
		for(const key in formData) {
			//检查 content 对象是否有名为 key 的自身属性。
			//如果有，则条件为真，执行 if 语句块中的代码；
			//如果没有，则为假，不执行 if 语句块中的代码
			if(Object.prototype.hasOwnProperty.call(content,key)) {
				formData[key] = content[key]
			}
		}
		
	})
}
</script>

<style lang="scss" scoped>

</style>